//
//  UserAccount.swift
//  mySina
//
//  Created by mac on 15/12/18.
//  Copyright © 2015年 tz. All rights reserved.
//

import UIKit
//自定义对象归档操作
class UserAccount: NSObject,NSCoding {
    //用于调用access_token，接口获取授权后的access token
    var access_token:String?
    //access_token的生命周期，单位是秒数
    var expires_in:NSTimeInterval = 0 {
        didSet {
            expires_data = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //Token的过期日期，开发者的是5年，普通账户的是3天
    var expires_data:NSDate?
    //当前授权用户的UID
    var uid:String?
    //友好显示名称
    var name: String?
    //用户头像地址（大图），180×180像素
    var avatar_large: String?
    //利用KVC给对象设置初始值
    init(dict:[String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    //打印格式
    override var description :String {
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_data"]
        return dictionaryWithValuesForKeys(keys).description
    }
    //保存自定义对象
    func saveAccount() {
        // String <-> NSString  [Key: Value] <-> NSDictnory  [xxx,xxx] <-> NSArray  在类型转换的时候 不需要考虑  ? 还是 !
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) .last! as NSString).stringByAppendingPathComponent("text.plist")
        //保存自定义对象
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    //从磁盘中解档数据
    //class表示类
    class func loadAccount() -> UserAccount? {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) .last! as NSString).stringByAppendingPathComponent("text.plist")
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount {
//            print("----------\(account)")
//            print(account.expires_data)
            //对Token的有效期做判断，如果过期，返回nil
            if account.expires_data?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
//                print("--------")
                return account
            }
        }
        return nil
    }
    //解档操作，将磁盘中得二进制数据转化成自定义的对象，
    required init?(coder aDcoder:NSCoder) {
        // as? 还是使用 as! 具体要看 接收或者需要使用的类型是可选还是必选
        access_token = aDcoder.decodeObjectForKey("access_token") as? String
        //如果基本数据类型 就可以直接获取到具体类型的熟悉 不需要类型转换
        expires_in = aDcoder.decodeDoubleForKey("expires_in")
        uid = aDcoder.decodeObjectForKey("uid") as? String
        name = aDcoder.decodeObjectForKey("name") as? String
        avatar_large = aDcoder.decodeObjectForKey("avatar_large") as? String
        expires_data = aDcoder.decodeObjectForKey("expires_date") as? NSDate
    }
    //归档操作，将自定义对象转换成二进制数据
    func encodeWithCoder(aCoder:NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(expires_data, forKey: "expires_date")
    }
}
